<?php

namespace App\Http\Controllers\Touch\Home;

use Illuminate\Http\Request;
use App\Http\Controllers\HomeController;
use Validator;

use App\Models\User;
use App\Models\Config;
use App\Models\SmsTpl;
use App\Models\Record\Send\Sms;
use Log;
use Crypt;
use Auth;

class AccountController extends HomeController
{
	/**
     * 发送手机验证码验证
     * @param  array  $data [description]
     * @return [type]       [description]
     */
    private function checkPhoneValidator(array $data)
    {
        $attribute =  array(
            'phone' => '手机号',
            'captcha' =>  '验证码',
        );

        $message  = array(
            'required' => ':attribute必须填写',
            'regex' => '手机号格式错误',
            'captcha' => '图片验证码错误',
        );
        return Validator::make($data, [
            'phone' => ['regex:/^(139|138|137|136|135|134|147|150|151|152|157|158|159|178|182|183|184|187|188|130|131|132|155|156|185|186|145|176|133|153|177|173|180|181|189|170|171)\d{8}$/'],
            'captcha' => 'bail|required|captcha',
        ],$message,$attribute);
    }

    /**
     * 绑定手机号验证
     * @param  array  $data [description]
     * @return [type]       [description]
     */
    private function checkBindPhoneValidator(array $data)
    {
        $attribute =  array(
            'phone' => '手机号',
            'code' =>  '验证码',
        );

        $message  = array(
            'required' => ':attribute必须填写',
            'regex' => '手机号格式错误',

        );
        return Validator::make($data, [
            'phone' => ['regex:/^(139|138|137|136|135|134|147|150|151|152|157|158|159|178|182|183|184|187|188|130|131|132|155|156|185|186|145|176|133|153|177|173|180|181|189|170|171)\d{8}$/'],
            'code' => 'bail|required',
        ],$message,$attribute);
    }


     /**
     * 密码验证
     * @param  array  $data [description]
     * @return [type]       [description]
     */
    private function checkPwdValidator(array $data){
        $attribute =  array(
            'password' => '密码',
            'captcha' =>  '验证码',
        );

        $message  = array(
            'required' => ':attribute必须填写',
            'confirmed' => ':attribute不相同',
            'min' => '最小:min字符',
            'max' => '最大:max字符',
            'captcha' => '图片验证码错误',
        );
        return Validator::make($data, [
           'password' => 'required|confirmed|min:6|max:15',
           'captcha' => 'bail|required|captcha',
        ],$message,$attribute);
    }

	/**
	 * 发送绑定手机验证码
	 * @return [type] [description]
	 */
    public function sendBindPhoneCode(Request $request){
    	$validator = $this->checkPhoneValidator($request->all());
        if($validator->fails()){
            $this->ajaxJson(1,$validator->errors()->first());
        }
        $phone = $request->input('phone');
        $this->checkUniquePhone($phone);

        $config = new Config();
        //获取短信服务商
        $smsConfig = $config->cacheFindByKey('sms');
        if(!$smsConfig || $smsConfig->vue==''){
        	Log::error("绑定手机号失败,未获取到全局sms配置");
        	$this->ajaxJson(1,'发送失败,请稍后重试');
        }
        $smsService = Config::where(['key'=>'sms_service','vue'=>$smsConfig->vue])->first();
        if(!$smsService){
        	Log::error("绑定手机号失败,未获取到sms_service短信服务商配置");
        	$this->ajaxJson(1,'发送失败,请稍后重试');
        }
        //获取短信服务商绑定手机号模版
        $smsTpl = SmsTpl::where(['config_id'=>$smsService->id,'module'=>'bindAccount'])->first();
        if(!$smsTpl){
        	Log::error("绑定手机号失败,未获取到短信服务商绑定短信模版");
        	$this->ajaxJson(1,'发送失败,请稍后重试');
        }
        //发送短信
        $result = $smsTpl->sendSms($phone,$smsConfig->vue,['code'=>substr(mt_rand(), 0,6),'product'=>'larvueadmin'],$request->getClientIp());
        if(!$result){
        	$this->ajaxJson(1,'发送失败,请稍后重试');
        }
        $this->ajaxJson(0,'发送成功',['key'=>Crypt::encrypt($result)]);
    }

    /**
     * 绑定手机号
     * @return [type] [description]
     */
    public function bindPhone(Request $request){
    	$validator = $this->checkBindPhoneValidator($request->all());
        if($validator->fails()){
            $this->ajaxJson(1,$validator->errors()->first());
        }
        $phone = $request->input('phone');
        $code = $request->input('code');
        if(!$request->input('key')){
        	$this->ajaxJson(1,'请获取手机验证码');
        }
        $smstpl_id = Crypt::decrypt($request->input('key'));
        $smsrecord = Sms::find($smstpl_id);
        //验证发送记录、是当前手机号发送、短信过期时间、短信验证码匹配 
        if(!$smsrecord || $smsrecord->phone!=$phone || json_decode($smsrecord->params,true)['code']!=$code ){
        	$this->ajaxJson(1,'验证码错误');
        }
        if(time()-strtotime($smsrecord->created_at)>$smsrecord->expireTime){
            $this->ajaxJson(1,'验证码已过期,请重新获取');   
        }
        if($smsrecord->isCheck){
        	$this->ajaxJson(1,'短信已失效,请重新获取');	
        }

        $this->checkUniquePhone($phone);

        //保存验证记录
        $smsrecord->isCheck = 1;
        $smsrecord->checkTime = date('Y-m-d H:i:s');
        $smsrecord->save();

        $user=Auth::user();
        $user->phone = $phone;
        $user->save();
        $this->ajaxJson(0,'绑定成功');
    }

    /**
     * 更新用户密码
     * @return [type] [description]
     */
    public function updatePwd(Request $request){
        $validator = $this->checkPwdValidator($request->all());
        if($validator->fails()){
            $this->ajaxJson(1,$validator->errors()->first());
        }
        $user=Auth::user();
        $user->password = bcrypt($request->input('password'));
        $user->save();
        Auth::guard()->logout();
        $request->session()->flush();
        $request->session()->regenerate();
        return $this->ajaxJson(0,'修改成功',[],false);
    }


    /**
     * 验证手机号已存在
     * @param  [type] $phone [description]
     * @return [type]        [description]
     */
    private function checkUniquePhone($phone){
    	//验证手机号已绑定
        $isBind = User::where(['phone'=>$phone])->count();
        if($isBind>0){
        	$this->ajaxJson(1,'手机号已被绑定,请更换一个手机号');
        }
    }
}
